<template>
  <div class="service-event-item-container">
    <div class="main">
      <div class="base-info">
        <div class="title">
          <i
            class="tag-color"
            :style="{ 'background-color': serviceEvent.config.color }"
          ></i>
          <h2 class="name">
            {{ serviceEvent.name }}
            <el-tooltip class="name-tips" trigger="hover" v-if="serviceEvent.name == '服务订单' && serviceEvent.isSystem == 1">
              <div slot="content">
                <span class="name-msg">{{$t('event.setting.serviceEventTypeSetting.manage.component.serviceEventItem.tips1')}}</span>
              </div>
              <i class="el-icon-question" />
          </el-tooltip>
          </h2>
        </div>
        <div class="other">
        <el-row type="flex" class="task-type-team-setting">
            <div @click="chooseTeam" class="pointer">
              <span style="color: #666666;">{{$t('task.setting.taskTypeSetting.manage.title10')}}: </span>
              <el-tooltip v-if="formatTeamName.length>15" trigger="hover">
                <div slot="content" style="width: 300px">{{formatTeamName}}</div>
                <span>{{formatTeamName.substring(0, 15)}}...{{$t('task.list.howMany', {ids: '', num: tagIds.length})}}</span>
              </el-tooltip>
              <span v-else>{{formatTeamName}}</span>
            </div>
            <i class="iconfont icon-edit-square pointer" @click="chooseTeam"></i>
          </el-row>
          <template v-if="isOpenData">
            <p>
              {{$t('common.base.newUpdate')}}:<open-data type="userName" :openid="serviceEvent.modifyStaffId"></open-data>{{ (serviceEvent.modifyTime || serviceEvent.createTime) | fmt_datetime }}
            </p>
          </template>
          <template v-else>
            <p>
              {{$t('common.base.lastUpdate')}}: {{serviceEvent.modifyUserName}}  {{(serviceEvent.modifyTime || serviceEvent.createTime) | fmt_datetime}}
            </p>
          </template>
        </div>
      </div>
      <div class="settings">
        <el-switch
         v-if="isShowEnabled"
          :value="serviceEvent.enabled"
          :active-value="1"
          :inactive-value="0"
          @change="handleSwitchEnabled"
        />
        <i class="iconfont icon-tuozhuaipaixu drag-icon"></i>
      </div>
    </div>
    <div class="operate">
      <div
        v-if="!isSystemServiceEvent"
        class="operate-del"
        @click="handleDelete"
      >
        <i class="iconfont icon-delete">{{$t('common.base.delete')}}</i>
      </div>
      <div class="operate-modify" @click="handleRouterGoEdit">
        <i class="iconfont icon-edit-square">{{$t('common.base.edit')}}</i>
      </div>
    </div>
      <!-- 选择团队弹窗 -->
      <choose-team-dialog
        type="event"
        :id="serviceEvent.id"
        :visiable.sync="isShowChooseTeamModal"
        :value="serviceEvent.tags"
        @update="updateTeamList"/>
  </div>
</template>

<script>
/* util */
import { debounce } from 'lodash';
import { isOpenData, openAccurateTab } from '@src/util/platform'
/** component */
import ChooseTeamDialog from '@src/modules/setting/task/taskTypeSetting/manage/components/ChooseTeamDialog.vue'
/* api */
import {
  enableEventType,
  deleteEventType,
} from '@src/api/SettingServiceEventApi';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
export default {
  name: 'service-event-item',
  props: {
    serviceEvent: { //  服务事件类型
      type: Object,
      default: () => ({}),
    },
    enableTypeNum: { // 已经开启的数量
      type: Number,
      default: 0
    },
    maxTypeNum: {// 最大可开启的事件类型
      type: Number,
      default: 0
    },
    teamList: {
      type: Array,
      default: () => []
    }
  },
  components: {
    [ChooseTeamDialog.name]: ChooseTeamDialog
  },
  data() {
    return {
      isOpenData,
      isShowChooseTeamModal: false
    };
  },
  computed: {
    /** 系统事件, isSystem= 1*/
    isSystemServiceEvent() {
      return this.serviceEvent.isSystem == 1;
    },
    /**
     * @description: 是否显示启用禁用按钮
     * @param {*} 1.非系统字段  2.是服务订单且是系统字段且位开启（兼容为了方便已经禁用的租户去开启）
     */    
    isShowEnabled() {
      const { isSystem, name, enabled } = this.serviceEvent;
      // return isSystem !==1 || (isSystem == 1 && name != '服务订单') || (isSystem == 1 && name == '服务订单' && enabled !=1 )
      return true

    },
    tagIds() {
      return this.serviceEvent.tagList || [];
    },
    formatTeamName() {
      let tagIds = this.tagIds;
      return tagIds.length === 0 ? this.$t('task.setting.taskTypeSetting.manage.allTeam') : this.$t('task.setting.taskTypeSetting.manage.individualTeam')
    },
  },
  methods: {
    updateTeamList(params) {
      const { checkedTeamList = [], requestParams = {} } = params
      // TODO  相关请求接口更新
      this.$emit('updateAttr', {  tags: checkedTeamList });
    },
    chooseTeam() {
      // this.isShowChooseTeamModal = true;
      this.$emit('handleChooseUseDept')
    },
    /** 启用/禁用 */
    handleSwitchEnabled: debounce(async function(value) {
      try {
        // 开启
        if(value == 1 && this.enableTypeNum >= this.maxTypeNum) return this.$message.warning(this.$t('event.setting.serviceEventTypeSetting.manage.component.serviceEventItem.tips2', {data1:this.maxTypeNum}))
        // 禁用
        if(value == 0 && this.enableTypeNum <= 1) return this.$message.warning(this.$t('event.setting.serviceEventTypeSetting.manage.component.serviceEventItem.tips3'))

        const { status, message } = await enableEventType({
          id: this.serviceEvent.id,
          enabled: value,
        });

        if (status == 0) {
          this.serviceEvent.enabled = value;
        } else {
          this.$message.warning(message);
        }
      } catch (e) {
        this.$message.warning(this.$t('common.base.tip.operationFail'));
      }
    }, 100),

    /** 删除事件类型*/
    async handleDelete() {
      try {
        if (this.isSystemServiceEvent) return this.$message.warning(this.$t('event.setting.serviceEventTypeSetting.manage.component.serviceEventItem.tips4'));

        const confirm = await this.$confirm( this.$t('event.setting.serviceEventTypeSetting.manage.component.serviceEventItem.tips5', {data1:this.serviceEvent.name}), this.$t('common.base.toast'), {
          confirmButtonText: this.$t('common.base.confirm'),
          cancelButtonText: this.$t('common.base.cancel'),
          type: 'warning',
        })
        if (!confirm) return;

        const res = await deleteEventType({
          typeId: this.serviceEvent.id, 
        });
        if (res.status == 0) {
          this.$message.success(this.$t('common.base.tip.deleteSuccess'));
          //  删除操作, 抛出更新操作(更新列表数据)
          this.$emit('update');
        } else {
          this.$message.warning(`${res.message}`);
        }        
      } catch (error) {
        console.warn(error)
      }

    },

    /** 编辑事件类型*/
    handleRouterGoEdit() {
      const id = this.serviceEvent.id;
      const fromId = window.frameElement.getAttribute('id');

      // this.$platform.openTab({
      //   id: 'service_event_flow_setting',
      //   title: '事件流程设置',
      //   url: `/setting/serviceStation/eventForm?serviceEventTypeId=${id}&new=true`,
      //   reload: true,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageEventFlowSetting,
        // titleKey: '事件流程设置',
        params: `serviceEventTypeId=${id}&new=true`,
        reload: true,
        fromId,
      })
    },
  },
};
</script>

<style lang="scss" scoped>
.service-event-item-container {
  min-height: 159px;
  background: #ffffff;
  box-shadow: 0px 2px 8px 0px rgba(0, 0, 0, 0.08);
  border-radius: 4px;
  &:hover {
    box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.12);
  }
  .main {
    display: flex;
    justify-content: space-between;
    height: calc(100% - 32px);
    padding: 16px 20px;
    .tag-color {
      display: block;
      width: 14px;
      min-width: 14px;
      height: 14px;
      line-height: 22px;
      margin: 3px 5px 0 0;
      border-radius: 50%;
    }
    .base-info {
      .title {
        display: flex;
      }
      .name {
        margin-bottom: 0;
        @include text-ellipsis-2;
        word-break: break-all;
        padding-right: 32px;
        line-height: 22px;
        height: 40px;
        font-size: 16px;
        color: #333333;
        &-tips {
          color: #666666;
        }
      }
      .other {
        margin-top: 8px;
        margin-left: 22px;
        p {
          margin-bottom: 6px;
          font-size: 12px;
          @include text-ellipsis-2;
          word-break: break-all;
          color: #666666;
          &:last-child {
            margin-bottom: 0;
          }
        }
        & > div:hover {
          p,
          i {
            color: $color-primary;
          }
        }
      }
    }
    .settings {
      display: flex;
      flex-direction: column;
      .drag-icon {
        display: none;
        margin-top: 23px;
        font-size: 12px;
        text-align: right;
      }
    }
  }
  .operate {
    display: flex;
    height: 32px;
    border-top: 1px solid#F5F5F5;
    & > div {
      cursor: pointer;
      flex: 1;
      text-align: center;
      line-height: 32px;
      color: #999999;
      i {
        font-size: 12px;
        &::before {
          margin-right: 8px;
        }
      }
    }
    .operate-del {
      border-right: 1px solid#F5F5F5;
      &:hover {
        color: $color-danger;
      }
    }
    .operate-modify {
      &:hover {
        color: $color-primary;
      }
    }
  }

  &:hover {
    cursor: move;
    .drag-icon {
      display: block !important;
    }
  }
}
.name-msg {
  width: 300px;
  display: inline-block;
  line-height: 18px;
}

@media screen and (max-width: 3000px) {
  .service-event-item {
    width: calc(100% / 6 - 12px);
  }
}
@media screen and (max-width: 2400px) {
  .service-event-item {
    width: calc(100% / 5 - 12px);
  }
}
@media screen and (max-width: 1925px) {
  .service-event-item {
    width: calc(100% / 4 - 12px);
  }
}
@media screen and (max-width: 1500px) {
  .service-event-item {
    width: calc(100% / 3 - 12px);
  }
}
@media screen and (max-width: 1200px) {
  .service-event-item {
    width: calc(100% / 2 - 12px);
  }
}
@media screen and (max-width: 900px) {
  .service-event-item {
    width: calc(100% - 12px);
  }
}
</style>
